#include "oled.h"

uint8_t Init_Settings[] = {
	    0xAE, // 关闭显示
	    0xD5, 0x80, // 设置显示时钟分频和振荡器频率
	    0xA8, 0x3F, // 设置多路复用率
	    0xD3, 0x00, // 设置显示偏移
	    0x40, // 设置显示起始行
	    0x8D, 0x14, // 启用电荷泵
	    0x20, 0x00, // 设置内存地址模式（水平地址模式）
	    0xA1, // 设置段重映射（列地址 127 映射到 SEG0）
	    0xC8, // 设置 COM 输出扫描方向（从 COM[N-1] 到 COM0）
	    0xDA, 0x12, // 设置 COM 引脚硬件配置
	    0x81, 0xCF, // 设置对比度
	    0xD9, 0xF1, // 设置预充电周期
	    0xDB, 0x40, // 设置 VCOMH 电平
	    0xA4, // 禁用全局显示
	    0xA6, // 设置正常显示模式（非反色）
	    0xAF  // 打开显示
	};

void Oled_Clear(){
	uint8_t i,n;
		for(i=0;i<8;i++)
		{
			Oled_Write_CMD(0xb0+i);
			Oled_Write_CMD (0x00);
			Oled_Write_CMD (0x10);
			for(n=0;n<128;n++)
				Oled_Write_Data(0);
		}
}


void Oled_Init(){
	HAL_Delay(200);

	// Initial Setting
	uint8_t i;
	for(i=0; i< (sizeof(Init_Settings)/sizeof(Init_Settings[0])); i++){
		HAL_I2C_Mem_Write(&hi2c1 ,0x78,0x00,I2C_MEMADD_SIZE_8BIT,Init_Settings + i,1,0x100);
	}
	Oled_Clear();

}

void Oled_Write_CMD(uint8_t cmd){
	HAL_I2C_Mem_Write(&hi2c1 ,0x78,0x00,I2C_MEMADD_SIZE_8BIT,&cmd,1,0x100);

}

void Oled_Write_Data(uint8_t data){

	HAL_I2C_Mem_Write(&hi2c1 ,0x78,0x40,I2C_MEMADD_SIZE_8BIT,&data,1,0x100);
}


void Oled_Display_On(void)
{
	Oled_Write_CMD(0X8D);  //SET DCD
	Oled_Write_CMD(0X14);  //DCDC ON
	Oled_Write_CMD(0XAF);  //DISPLAY ON
}

void OLED_Display_Off(void)
{
	Oled_Write_CMD(0X8D);  //SET DCD
	Oled_Write_CMD(0X10);  //DCDC OFF
	Oled_Write_CMD(0XAE);  //DISPLAY OFF
}

void Oled_Set_Pos(uint8_t x, uint8_t y)
{
	Oled_Write_CMD(0xb0+y);
	Oled_Write_CMD(((x&0xf0)>>4)|0x10);
	Oled_Write_CMD(x&0x0f);
}
// x ~ [0~127], y ~ [0, 64]
void Oled_Show_Char(uint8_t x,uint8_t y,uint8_t chr,uint8_t Char_Size)
{
	unsigned char c=0,i=0;
		c=chr-' ';
		if(x>128-1){x=0;y=y+2;}
		if(Char_Size ==16){
			Oled_Set_Pos(x,y);
			for(i=0;i<8;i++){
				Oled_Write_Data(F8X16[c*16+i]);
			}

			Oled_Set_Pos(x,y+1);
			for(i=0;i<8;i++){
				Oled_Write_Data(F8X16[c*16+i+8]);
			}

		}
		else {
			Oled_Set_Pos(x,y);
			for(i=0;i<6;i++)
			{
				Oled_Write_Data(F6x8[c][i]);
			}


		}
}


void Oled_Show_String(uint8_t x,uint8_t y,uint8_t *chr,uint8_t Char_Size)
{
	unsigned char j=0;
		while (chr[j]!='\0')
		{		Oled_Show_Char(x,y,chr[j],Char_Size);
				x+=8;
			if(x>120){x=0;y+=2;}
				j++;
		}

}








